//$Id: rebuild.js,v 1.9 2008/10/18 18:25:04 silviogutierrez Exp $

var GallerixRebuild = GallerixRebuild || {};

$(document).ready(function() {
  
  GallerixRebuild.settings = Drupal.settings.gallerixRebuild;

  $('.gallerix-rebuild').click(function() {

    GallerixRebuild.beginRebuild(GallerixRebuild.getID(this.id));
    return false;
  });

});





/**
 * Get the action from a button using it's CSS.
 *
 */
GallerixRebuild.getID = function (css) {
  var index = css.lastIndexOf('-');

  return css.substring(index + 1); 
}





/**
 * Begin the rebuilding process. Loop continuously until there are no more
 * pictures to rebuild. Add a progress bar to keep track of everything.
 *
 */
GallerixRebuild.beginRebuild = function(operation) {

  //Figure out which operations were requested.
  if (operation != 'all') {
    var operations = operation;
  }
  else {
    var operations = 'derivatives|#|exif|#|iptc|#|sort';
  }
  
  GallerixRebuild.settings.threshold = $('#edit-threshold').val();
  
  //If there's a previous progress bar, remove it.
  $('#progress').remove(); 
  
  //Append the progress bar to the right operation.
  $('#gallerix-fieldset-' + operation).append(GallerixRebuild.settings.progressBar);
  
  $('.gallerix-rebuild').attr('disabled', 'disabled');
  GallerixRebuild.rebuild(0, operations);

} 
 
 
 
GallerixRebuild.rebuild = function(current, operations) {
  var url = GallerixRebuild.settings.rebuildURL + current + '/' + GallerixRebuild.settings.threshold;

  $.post(url, {gallerix_operations : operations}, function(data) {
    var response = Gallerix.parseJson(data);
    
    $('#progress > div.percentage').html(response.percentage + '%');
    $('#progress div.filled').css('width', response.percentage + '%');
        
    if (response.status == 'continue') {
      GallerixRebuild.rebuild(response.current, operations);
    }
    else {
      $('#progress > div.message').html("Finalizing");
          
      $.get(GallerixRebuild.settings.finalizeURL + GallerixRebuild.settings.threshold, null, function() {
        $('.gallerix-rebuild').attr('disabled', '');
        $('#progress > div.message').html("Rebuilding Complete");       
      });
    }
    
  });  

} 






